// mine.js
const App = getApp()
var req = require('../../utils/reqUtils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidePopup:true,
    loadingHidden:false,
    phoneNumber:'请输入',
    userInfo: {
      'username':'请登录',
    },
    code:'',
    iv:'',
    encryptedData:'',
    coaches:{},
    avatarUrl:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
    avatarId:'',
    items: [
      // {
      //   icon: '../../images/mine/Fingerprint.png',
      //   text: '每日打卡',
      //   path: '/pages/signin/sign-in',
      //   type:1
      // },
      {
        icon: '../../images/mine/ok.png',
        text: '会员卡',
        path: '/pages/shop-cart/index',
        type:1
      },
      {
        icon: '../../images/mine/order.png',
        text: '已预订课程',
        path: '/pages/order-list/index',
        type:1
      },
      {
        icon: '../../images/mine/phone.png',
        text: '我的信息',
        path: '',
        type:2
      },
      {
        icon: '../../images/mine/phone.png',
        text: '人脸录入',
        path: '/pages/my-face/my-face',
        type:1
      },
      {
        icon: '../../images/mine/support.png',
        text: '联系客服',
        path: '',
        type:3
      },
    ],
    settings: [
      // {
      //   icon: '../../images/mine/About-Us.png',
      //   text: '关于我们',
      //   path: '/pages/articles-detail/index?id=742',
      //   type:1
      // },
      {
        icon: '../../images/mine/support.png',
        text: '学员信息',
        path: '/pages/my-trainee/my-trainee',
        type:1
      },
      {
        icon: '../../images/mine/support.png',
        text: '课程安排',
        path: '/pages/my-course/my-course',
        type:1
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // wx.getStorageSync("userInfo");
    if(wx.getStorageSync("userInfo")){
      req.post('/getUserInfo/index',{'id':wx.getStorageSync("userInfo")['u_id']},1).then(res=>{
        if(!(res.data.status == 201)){
          res.data.userInfo.coach_id = 9;
          wx.setStorageSync('userInfo', res.data.userInfo)
          console.log(res.data.userInfo.coach_id); 
        }else{
          wx.setStorageSync('userInfo', {})
        }
        that.setData({
          userInfo: wx.getStorageSync("userInfo"),
          coaches: wx.getStorageSync("coachInfo"),
          avatarUrl:'https://nt.yuntaihang.com/'+wx.getStorageSync("userInfo")['avatar']
        })
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "拿铁之家运动空间",
      path:"/pages/home/home"
    }
  },
  //获取用户信息
  // getUserInfo:function() {
  //   var userInfo = App.globalData.userInfo
  //   var that = this;

  //   if (userInfo) {
  //     that.setData({
  //       userInfo: userInfo
  //     })
  //     return
  //   }

  //   userInfo = App.getUserInfo();
  //   console.log(userInfo);
  //   that.setData({
  //     userInfo: userInfo
  //   })
  // },

  bindtap(e) {
  },
  navigateTo:function(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    const path = e.currentTarget.dataset.path;
    var that = this;
    console.log(that.userInfo);
    if(!that.userInfo){
      console.log('未登录')
      wx.showLoading({
        title: '登录中',
      })
      wx.login({
        success (res) {
          console.log(res);
          if (res.code) {
            wx.getUserInfo({
              success: function(resU) {
                console.log(resU.userInfo)
                that.code = res.code
                wx.request({
                  url: 'http://local.yj.com/login/index',  
                  // url: 'https://nt.yuntaihang.com/login/index',  
                  header: {
                    'Content-Type':  'application/json ',
                  },
                  data: {
                    'code':that.code,
                  },
                  method: 'POST',
                  success: function (res) {
                    console.log(res);
                    if(res.data.status == 0){
                      that.setData({
                        userInfo: res.data.datainfo
                      })
                      wx.setStorage({
                        key:"userInfo",
                        data:res.data.datainfo
                      })
                      that.userInfo = res.data.datainfo
                      wx.hideLoading();
                      console.log(that.userInfo);
                      // that.globalData.userInfo= that.userInfo;
                    }
                      
                  }
                }) 
                
              }
            })
            // console.log(res.code)
            // return;

          } else {
            console.log('登录失败！' + res.errMsg)
          }
        },fail: (res) => {
                // debugger;
                console.log(res);
            }
      })
      // wx.getUserProfile({
      //   desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      //   success: (resU) => {
      //     console.log(resU);
      //     that.encryptedData = resU.encryptedData;
      //     that.iv = resU.iv;

      //   },
      //   fail: (resU) => {
      //       debugger;
      //       console.log(resU);
      //   }
      // })
      
     
      

      return;
    }      
    console.log(type);
    switch (type) {
      case 2:
        this.showPopupTap();
        break;
      case 3:
        wx.makePhoneCall({
          phoneNumber: path
        })
        break;
      // case 4:
      //   wx.makePhoneCall({
      //     phoneNumber: path
      //   })
      // break;
      default:
        console.log(path);
        // console.log(typeof path);
        wx.navigateTo({
          url: path
        });
    };
  },
  onChooseAvatar(e) {
    var that = this;
    const { avatarUrl } = e.detail;
    wx.uploadFile({
      url: "https://nt.yuntaihang.com/up_image/index",
      filePath: avatarUrl,
      name: 'file',
      formData: {
        'openid': wx.getStorageSync('openid')
      },
      success(res) {
        const data = JSON.parse(res.data)
        console.log(data);
        that.setData({
          avatarUrl:'https://nt.yuntaihang.com/'+data.data.src,
          avatarId:data.data.id
        })
      },
      fail(res) {
        console.log('upload fail');
      }
    })
    // console.log(e.detail);
  //   req.post('/upImage/index',{'target': e.detail.avatarUrl},1).then(res=>{
  //     console.log(res);
  // })
    // this.setData({
    //   avatarUrl,
    // })
  },
  closePopupTap: function () {
    this.setData({
      hidePopup: true
    })
  },
  showPopupTap: function () {
    this.setData({
      hidePopup: false
    })
  },
  formSubmit:function(e){
    var that = this;
    console.log(this.data.avatarId);
    console.log(e.detail);
    var dataId = 0;
    var postData = {
      'u_id':wx.getStorageSync('userInfo')['u_id'],
      'username':e.detail.value.nickname,
      'mobile':e.detail.value.phoneNumber
    }
    if(this.data.avatarId){
      postData.avatar = this.data.avatarId
    }
  //  console.log(dataId);
    // return;
    var phone = e.detail.value.phoneNumber;
    if (phone.length != 11 && phone.length != 8){
      wx.showModal({
        title: '提示',
        content: '电话号码不正确，请确认后重新输入。',
      });
      return;
    }
    postData.openid = this.userInfo.openid;
    req.post('/edit_user_info/index',postData,1).then(res=>{
      if(res.data.userInfo){
        wx.setStorageSync('userInfo', res.data.userInfo);
        that.setData({
          'userInfo':res.data.userInfo
        })
      }
        // console.log(res);
        
    })
    this.closePopupTap();
    return;
    const phoneNumber = e.detail.value.phoneNumber;
    if (phoneNumber.length != 11 && phoneNumber.length != 8){
      wx.showModal({
        title: '提示',
        content: '电话号码不正确，请确认后重新输入。',
      });
      return;
    }
    this.setData({
      phoneNumber: e.detail.value.phoneNumber
    });
    wx.setStorageSync({
      key: "phoneNumber",
      data: phoneNumber
    });
    this.closePopupTap();
  },
  navigateToLogin:function(){
    wx.navigateTo({
      url: '/pages/login/login'
    });
  }
})

/*
import __config from '../../etc/config'
const App = getApp()

Page({
	data: {
		userInfo: {},
		items: [
			{
				icon: '../../assets/images/iconfont-order.png',
				text: '我的订单',
				path: '/pages/order/list/index'
			},
			{
				icon: '../../assets/images/iconfont-addr.png',
				text: '收货地址',
				path: '/pages/address/list/index'
			},
			{
				icon: '../../assets/images/iconfont-kefu.png',
				text: '联系客服',
        path: '400-0728-156',
			},
			{
				icon: '../../assets/images/iconfont-help.png',
				text: '常见问题',
				path: '/pages/help/list/index',
			},
		],
		settings: [
			{
				icon: '../../assets/images/iconfont-clear.png',
				text: '清除缓存',
				path: '0.0KB'
			},
			{
				icon: '../../assets/images/iconfont-about.png',
				text: '关于我们',
				path: '/pages/about/index'
			},
		]
	},
	onLoad() {
		this.getUserInfo()
		this.getStorageInfo()
	},
	navigateTo(e) {
		const index = e.currentTarget.dataset.index
		const path = e.currentTarget.dataset.path

		switch(index) {
			case 2:
				App.WxService.makePhoneCall({
					phoneNumber: path
				})
				break
			default:
				App.WxService.navigateTo(path)
		}
    },
    getUserInfo() {
    	const userInfo = App.globalData.userInfo

		if (userInfo) {
			this.setData({
				userInfo: userInfo
			})
			return
		}

		App.getUserInfo()
		.then(data => {
			console.log(data)
			this.setData({
				userInfo: data
			})
		})
    },
    getStorageInfo() {
    	App.WxService.getStorageInfo()
    	.then(data => {
    		console.log(data)
    		this.setData({
    			'settings[0].path': `${data.currentSize}KB`
    		})
    	})
    },
    bindtap(e) {
    	const index = e.currentTarget.dataset.index
		const path = e.currentTarget.dataset.path

		switch(index) {
			case 0:
				App.WxService.showModal({
		            title: '友情提示',
		            content: '确定要清除缓存吗？',
		        })
		        .then(data => {
              if(data.confirm == 1)
              {
                App.WxService.clearStorage()
                this.signIn()
              }
            })
				break
			default:
				App.WxService.navigateTo(path)
		}
    },
    // logout() {
    // 	App.WxService.showModal({
    //         title: '友情提示',
    //         content: '确定要登出吗？',
    //     })
    //     .then(data => data.confirm == 1 && this.signOut())
    // },
    // signOut() {
    // 	App.HttpService.signOut()
    // 	.then(data => {
    // 		console.log(data)
    // 		if (data.meta.code == 0) {
    // 			App.WxService.removeStorageSync('token')
    // 			App.WxService.redirectTo('/pages/login/index')
    // 		}
    // 	})
    // },
    signIn() {
      if (App.WxService.getStorageSync('token')) return
      App.HttpService.signIn({
        username: __config.loginItem.name,
        password: __config.loginItem.psw,
      })
        .then(data => {
          console.log(data)
          if (data.meta.code == 0) {
            App.WxService.setStorageSync('token', data.data.token)
          }
        })
    },
})
 */